package by.grsu.matrenichev.page.student;

import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.Model;
import org.apache.wicket.spring.injection.annot.SpringBean;

import by.grsu.matrenichev.dao.StudentDao;
import by.grsu.matrenichev.entity.Student;
import by.grsu.matrenichev.page.BasePage;

public class EditStudentPage extends BasePage {

	@SpringBean
	private StudentDao studentDao;

	@SuppressWarnings("serial")
	public EditStudentPage(final Student studentToEdit) {
		super();

		// create form fields and set data
		final TextField<String> firstnameField = new TextField<String>("firstname", new Model<String>(studentToEdit.getFirstname()));
		final TextField<String> lastnameField = new TextField<String>("lastname", new Model<String>(studentToEdit.getLastname()));
		final TextField<String> testnameField = new TextField<String>("testname", new Model<String>(studentToEdit.getTestname()));
		final TextField<String> subjectField = new TextField<String>("subject", new Model<String>(studentToEdit.getSubject()));
		final TextField<Integer> markField = new TextField<Integer>("mark", new Model<Integer>(studentToEdit.getMark()));
		markField.setType(Integer.class);
		
		// create "form" component which is required for data retrieving from
		// client to server
		Form<Student> form = new Form<Student>("form", new Model<Student>(studentToEdit)) {
			@Override
			public void onSubmit() {
				// retrieve data from the form and set it to the object
				studentToEdit.setFirstname(firstnameField.getModelObject());
				studentToEdit.setLastname(lastnameField.getModelObject());
				studentToEdit.setTestname(testnameField.getModelObject());
				studentToEdit.setSubject(subjectField.getModelObject());
				studentToEdit.setMark(markField.getModelObject());
				// save updated object in DB
				studentDao.save(studentToEdit);
				// go to the list page
				setResponsePage(ListStudentPage.class);
			}
		};

		// add form fields
		form.add(firstnameField);
		form.add(lastnameField);
		form.add(testnameField);
		form.add(subjectField);
		form.add(markField);

		// add buttons
		form.add(new Button("saveLink"));
		form.add(new Link<Student>("cancelLink") {
			private static final long serialVersionUID = -1521748836027504873L;

			@Override
			public void onClick() {
				setResponsePage(ListStudentPage.class);
			}
		});
		// add form to the page
		add(form);

		// add special component which will allow to display "validation errors"
		// and feedback messages
		FeedbackPanel feedbackPanel = new FeedbackPanel("feedback");
		add(feedbackPanel);
	}

}
